local MapPoint = require("app.map.MapPoint")

local PlayerMoveQueue = class("PlayerMoveQueue")--record move path

function PlayerMoveQueue:ctor(delegate)
    self.mDelegate = delegate
    self.mPlayer = delegate:getCurrPlayer()
    self.targetPosQueue = {}
    self.bMoving = false
    self.moveDir = cc.p(0,0)
    self.nStep = 0 --60frames/1s : 60steps = speed:1s
end

function PlayerMoveQueue:arrived(isCurrGrid)    
    if #self.targetPosQueue <= 0 then
        self.mNextTar = nil
        self.mDelegate:playAnimation(FigureState.Stand,self.moveDir)
    else
        self:walkOneStep()
    end
    if not isCurrGrid then
        self.mDelegate:arriveNextGrid()
    end
end

function PlayerMoveQueue:walkOneStep()
    local target = table.remove(self.targetPosQueue,1)
    if not target then
        return
    end
    local m_gird = MapPoint.new(cc.p(self.mPlayer:getPosition()))
    if target and MapPoint.equalsObj(target,m_gird) then
       self:arrived(true)
       return
    end
    self.mNextTar = target
    self.moveDir = cc.p(target.x-m_gird.x,target.z-m_gird.z) -- (1,0) (0,1) (1,1)
    self.mDelegate:playAnimation(FigureState.Run,self.moveDir) 
    self.nStep = 0
    self.bMoving = true
end

function PlayerMoveQueue:goto(posList)
    self:clearCurrentQueue()
    self.targetPosQueue = posList
    if not self.bMoving then
        self:walkOneStep()
    end
end

function PlayerMoveQueue:stop()
    self.bMoving = false
    self.mNextTar = nil
    self:clearCurrentQueue()
end

function PlayerMoveQueue:clearCurrentQueue()
    self.targetPosQueue = {}
end

function PlayerMoveQueue:update()
    if self.bMoving then
        local pos = cc.p(self.mPlayer:getPosition())
        local step_len = self.mDelegate.nMoveStep/self.mDelegate.nCurFrame --每帧走的距离
        local ptMap = cc.p(MapPoint.GRID_SIZE.width*self.moveDir.x,MapPoint.GRID_SIZE.height*self.moveDir.y) --单个网格的长度分量
        local totalSteps = cc.pGetLength(cc.pMul(ptMap,1/step_len)) --完成一格的总帧数
        local curtpos = cc.pAdd(pos,cc.pMul(cc.pNormalize(ptMap),step_len)) --当前帧所在的位置
        local step_extra = totalSteps-math.floor(totalSteps) --帧多余的小数位
        if self.nStep+1==math.floor(totalSteps) and step_extra>0  then
            --最后一帧时将位置拉倒格子的中点
            curtpos =self.mNextTar:getCCPointValue()
            --curtpos = cc.pAdd(pos,cc.pMul(cc.pNormalize(ptMap),step_len*(1+step_extra/step_len)))
        end
        --print(self.nStep,curtpos.x,curtpos.y)
        self.mPlayer:setPosition(curtpos)
        self.nStep = self.nStep+1
        if self.nStep >= math.floor(totalSteps) then
            self.bMoving = false
            self:arrived()
        end
    end
end

function PlayerMoveQueue:getNextTarGrid()
    return self.mNextTar
end

return PlayerMoveQueue